package com.zzyk.web.controller;

import com.github.pagehelper.PageInfo;

import com.zzyk.main.configuration.aspectj.annotation.OperaLog;
import com.zzyk.main.configuration.exception.UserException;
import com.zzyk.main.controller.BaseController;
import com.zzyk.main.model.pojo.RolePermission;
import com.zzyk.main.model.pojo.SysRole;
import com.zzyk.main.model.pojo.SysUser;
import com.zzyk.main.model.vo.Message;
import com.zzyk.main.service.ISysPermissionService;
import com.zzyk.main.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/sys/role")
public class SysRoleController extends BaseController {

    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysPermissionService sysPermissionService;

    @GetMapping("getRoleList")
    public Message getRoleList() throws UserException {
        SysUser user = currentUser();
        if (user.getReadonly() == 1) {
            return listRole(null);
        }
        return Message.success().addData("data", sysRoleService.getOrdinaryRole());
    }

    /**
     * 列出所有的角色 支持模糊查询和精准查询 具体见mapper定义
     *
     * @param sysRole 模糊查询关键字 searchValue
     * @return 符合上列条件的角色
     */
    @RequestMapping("list")
    public Message listRole(SysRole sysRole) throws UserException {
        setPage();
        if (!hasRole(1) && !hasRole(2)) {
            sysRole.setType(1);
        }
        Message message = Message.success("角色查询成功");
        List<SysRole> list = sysRoleService.getRoleList(sysRole);
        PageInfo<SysRole> info = new PageInfo<>(list);
        message.addData("data", info.getList());
        message.addData("total", info.getTotal());
        message.addData("pages", info.getPages());
        return message;
    }

    /**
     * 查询具体某个角色的详细信息
     *
     * @param roleId 角色ID
     * @return 该角色的纤细信息
     */
    @RequestMapping("info")
    public Message rolePermission(@RequestParam("roleId") Integer roleId) {
        Message message = Message.success();
        message.addData("data", sysRoleService.getRole(roleId));
        return message;
    }

    /**
     * 用来新增或更新角色
     *
     * @param sysRole        系统角色
     * @param permissionList 给该角色分配的权限
     * @return 成功
     * @throws UserException 失败
     */
    @OperaLog("修改角色信息")
    @RequestMapping("save")
    @Transactional
    public Message saveRole(SysRole sysRole,
                            @RequestParam(value = "permissionList[]", required = false) Integer[] permissionList) throws UserException, MissingServletRequestParameterException {
        if (sysRole == null) {
            throw new MissingServletRequestParameterException("sysRole", SysRole.class.getName());
        }
        // 如果ID为空则为新增 否则为更新
        // 不管是那个都要确保在角色新增或更新完成之后再更新权限
        if (sysRole.getId() == null) {
            if (sysRoleService.getRole(sysRole.getRoleName()) != null) {
                throw new UserException("已存在同名系统角色");
            }
            if (sysRoleService.addRole(sysRole) > 0) {
                if (permissionList != null) {
                    updateRolePermission(sysRole, permissionList);
                }
                return Message.success("系统角色添加完成");
            } else {
                throw new UserException("系统角色添加失败");
            }
        } else {
            if (sysRoleService.updateRole(sysRole) > 0) {
                // 如果是更新角色则要先删除该角色的所有权限然后重新添加
                sysPermissionService.deleteRolePermissionByRoleId(sysRole.getId());
                if (permissionList != null) {
                    updateRolePermission(sysRole, permissionList);
                }
                return Message.success("系统角色修改完成");
            } else {
                throw new UserException("系统角色修改失败");
            }
        }
    }

    /**
     * 删除系统角色
     *
     * @param id 角色ID
     * @return 成功
     * @throws UserException 失败
     */
    @OperaLog("删除角色信息")
    @RequestMapping("del")
    @Transactional
    public Message delRole(@RequestParam("id") Integer id) throws UserException {
        if (sysRoleService.deleteRole(id) <= 0) {
            throw new UserException("删除失败");
        }
        sysPermissionService.deleteRolePermissionByRoleId(id);
        return Message.success("删除成功");
    }

    /**
     * 更新角色权限
     *
     * @param sysRole        系统角色
     * @param permissionList 权限数组
     */
    private void updateRolePermission(SysRole sysRole, Integer[] permissionList) {
        List<RolePermission> rolePermissionList = new ArrayList<>();
        for (Integer permissionId : permissionList) {
            RolePermission rp = new RolePermission();
            rp.setRoleId(sysRole.getId());
            rp.setPermissionId(permissionId);
            rolePermissionList.add(rp);
        }
        sysPermissionService.addRolePermission(rolePermissionList);
    }
}
